package com.lianzhihui.romeex.ui.account;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.github.lzyzsd.jsbridge.DefaultHandler;
import com.google.android.material.tabs.TabLayout;
import com.google.zxing.client.android.Intents;
import com.lianzhihui.romeex.R;
import com.lianzhihui.romeex.bean.user.CountryCode;
import com.lianzhihui.romeex.bean.user.WalletInfo;
import com.lianzhihui.romeex.config.AppConstants;
import com.lianzhihui.romeex.config.DataManager;
import com.lianzhihui.romeex.database.DataBaseManager;
import com.lianzhihui.romeex.inter.CustomCallback;
import com.lianzhihui.romeex.mvp.presenter.SyncUserPresenter;
import com.lianzhihui.romeex.mvp.view.SyncUserView;
import com.lianzhihui.romeex.ui.base.BaseActivity;
import com.lianzhihui.romeex.ui.qrcode.ScanActivity;
import com.lianzhihui.romeex.utils.AESCrypt;
import com.lianzhihui.romeex.utils.JS2AndroidUtil;
import com.lianzhihui.romeex.utils.LogUtil;
import com.lianzhihui.romeex.utils.MyToast;
import com.lianzhihui.romeex.utils.QrUtils.QRUtils;
import com.lianzhihui.romeex.utils.UserUtils;
import com.lianzhihui.romeex.mvp.view.LoginView;
import com.lianzhihui.romeex.widget.dialog.CommonConfirmDialog;

import java.security.GeneralSecurityException;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.realm.Realm;

import static com.lianzhihui.romeex.ui.MainActivity.reLogin;

/**
 * ProjectName:    NBN
 * ClassName:      ImportWalletActivity
 * Description:    导入钱包
 * Author:         echo
 * CreateDate:     2019/11/21 11:23
 * UpdateUser:     更新者
 * UpdateDate:     2019/11/21 11:23
 * UpdateRemark:   更新说明
 * Version:        1.0
 */
public class ImportWalletActivity extends BaseActivity implements LoginView, SyncUserView, Realm.Transaction.OnSuccess {

    @BindView(R.id.mBridgeWebView)
    BridgeWebView mBridgeWebView;
    @BindView(R.id.tv_mnemonic_word)
    TextView tv_mnemonic_word;
    @BindView(R.id.tv_tips)
    TextView tv_tips;
    @BindView(R.id.et_account_name)
    EditText et_account_name;
    @BindView(R.id.et_safty_code)
    EditText et_safty_code;
    @BindView(R.id.et_safty_code_again)
    EditText et_safty_code_again;
    @BindView(R.id.rl_safty_code_again)
    View rl_safty_code_again;
    @BindView(R.id.tabLayout)
    TabLayout tabLayout;
    @BindView(R.id.iv_scan)
    ImageView iv_scan;


    private SyncUserPresenter syncUserPresenter;
    private JS2AndroidUtil jS2AndroidUtil;
    private boolean finishLoad = false;
    private int IMPORT_TYPE = 1;
    private String passWord;
    private String account;
    private boolean isManage;
    //全局钱包实体
    private WalletInfo walletInfo;

    private static final String DECODED_CONTENT_KEY = "codedContent";
    private static final String DECODED_BITMAP_KEY = "codedBitmap";
    private static final int REQUEST_CODE_SCAN = 0x0000;
    private String stringResPk;
    private boolean showCurrentIndexFlag = false;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_import_wallet;
    }

    @Override
    protected void initView() {
        setTitle(getString(R.string.import_wallet));

        isManage = getIntent().getBooleanExtra("isManage", false);
        syncUserPresenter = new SyncUserPresenter(this, this);
        jS2AndroidUtil = new JS2AndroidUtil(this, this);
        mBridgeWebView.addJavascriptInterface(jS2AndroidUtil, "Android");
        mBridgeWebView.setDefaultHandler(new DefaultHandler());
        mBridgeWebView.loadUrl("file:///android_asset/index.html");
        mBridgeWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                if (newProgress == 100) {
                    finishLoad = true;
                }
            }
        });
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                chooseItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    @Override
    protected void initData() {
        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            stringResPk = extras.getString(AppConstants.RESPK, "");
            showCurrentIndexFlag = true;
        }
    }

    /**
     * 导入钱包
     *
     * @param words
     * @param password
     */
    public void importWallet(String words, String password) {
        passWord = password;
        showLoading(getResources().getString(R.string.loading_import_wallet));
        jS2AndroidUtil.setWalletType(2);
        String jsFunction = null;
        switch (IMPORT_TYPE) {
            case 1://助记词
                jsFunction = "javascript:importWallet('" + words + "')";
                break;
            case 2://KeyStore
                jsFunction = "javascript:importWalletByKeystore('" + words + "','" + passWord + "')";
                break;
            case 3://私钥
                jsFunction = "javascript:importWalletByWIF('" + words + "')";
                break;
        }

        mBridgeWebView.evaluateJavascript(jsFunction, new ValueCallback<String>() {
            @Override
            public void onReceiveValue(String data) {
                dismissLoading();
            }
        });
    }

    /**
     * 设置安全码
     */
    private void setCode() {

        String mnemonic_word = tv_mnemonic_word.getText().toString().trim();
        account = et_account_name.getText().toString().trim();
        String code = et_safty_code.getText().toString().trim();
        String codeAgain = et_safty_code_again.getText().toString().trim();

        if (TextUtils.isEmpty(account)) {
            MyToast.showToast(getResources().getString(R.string.toast_input_account));
            return;
        }
        if (code.length() < 6) {
            MyToast.showToast(getResources().getString(R.string.toast_veryfy_not_enough));
            return;
        }
        if (IMPORT_TYPE == 2) {
            if (code.length() == 6) {
                importWallet(mnemonic_word, code);
            } else {
                Toast.makeText(mActivity, getResources().getString(R.string.toast_veryfy_not_enough), Toast.LENGTH_SHORT).show();
                return;
            }
        } else {
            if (TextUtils.isEmpty(codeAgain)) {
                MyToast.showToast(getResources().getString(R.string.toast_input_code_again));
                return;
            }
            if (!TextUtils.isEmpty(account) && !TextUtils.isEmpty(code)) {
                if (code.equals(codeAgain)) {
                    importWallet(mnemonic_word, codeAgain);
                } else {
                    Toast.makeText(mActivity, getResources().getString(R.string.toast_veryfy_code_not_equals), Toast.LENGTH_SHORT).show();
                    return;
                }
            }
        }
    }

    /**
     * 添加钱包到本地
     *
     * @param walletInfo
     */
    private void addWalletInfo(WalletInfo walletInfo) {
        if (!this.isDestroyed()) {
            LogUtil.error("ramon", "addWalletInfo: " + walletInfo.toString());
            walletInfo.setUserName(account);

            try {
                String privateKeyAES = AESCrypt.encrypt(passWord + AESCrypt.SerectAppend, walletInfo.getCompressedPrivkey());
                walletInfo.setCompressedPrivkey(privateKeyAES);
            } catch (GeneralSecurityException e) {
                e.printStackTrace();
            }

            walletInfo.setSaftyCode(passWord + AESCrypt.SerectAppend);
            this.walletInfo = walletInfo;
            //检查是否已存在的用户，如果已存在，提示跳转至钱包管理
            WalletInfo tempUser = UserUtils.getUser(walletInfo.getAddress());

            if (tempUser == null) {
                //todo 用户不存在，新增导入，设为当前用户
                showLoading(getResources().getString(R.string.loading_sync));
                DataManager.setUserInfo(walletInfo);
                syncUserPresenter.syncUser(walletInfo.getAddress());
            } else {
                //用户存在，跳转钱包管理
                new CommonConfirmDialog(this, getResources().getString(R.string.import_wallet_exist_configm), new CustomCallback() {
                    @Override
                    public void onCompare(Object o) {
                        //todo 已存在导入 跳转 钱包管理
                        finish();
                    }
                }).show();
            }
        }

    }

    @Override
    public void onSuccess() {

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (showCurrentIndexFlag) {
            TabLayout.Tab tabAt = tabLayout.getTabAt(1);
            if (tabAt != null) {
                tabAt.select();
            }
            tv_mnemonic_word.setText(stringResPk);
            showCurrentIndexFlag = false;
        }

    }

    @Override
    public void setAccountData(WalletInfo data) {

    }

    /**
     * 导入 返回数据
     *
     * @param data
     */
    @Override
    public void setImportData(WalletInfo data) {
        //todo 生成导入用户数据
        walletInfo = data;
//        Log.e("ramon", "导入数据：" + data.toString());
        Log.e("ramon", "setImportData：" + data.toString());

        if (TextUtils.isEmpty(data.getAddress())) {
            switch (IMPORT_TYPE) {
                case 1:
                    MyToast.showToast(getResources().getString(R.string.import_wallet_memryword_err));
                    break;
                case 2:
                    MyToast.showToast(getResources().getString(R.string.import_wallet_keystore_err));
                    break;
                case 3:
                    MyToast.showToast(getResources().getString(R.string.import_wallet_privatekey_err));
                    break;
            }
            return;
        }

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                getKeyStore(data.getCompressedPrivkey(), passWord);
            }
        });

    }

    @Override
    public void setWalletData(WalletInfo data) {
        LogUtil.error("ramon", "setWalletData: " + data.toString());
        walletInfo.setCiphertext(data.getCiphertext());
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                addWalletInfo(walletInfo);
            }
        });
    }

    /**
     * 生成 ks
     *
     * @param pk
     * @param safetycode
     */
    public void getKeyStore(String pk, String safetycode) {
        showLoading("");
        jS2AndroidUtil.setWalletType(3);
        LogUtil.error("ramon", "getKeyStore");
        String jsFunction = "javascript:pk2Keystore('" + pk + "','" + safetycode + "')";
        mBridgeWebView.evaluateJavascript(jsFunction, new ValueCallback<String>() {
            @Override
            public void onReceiveValue(String data) {
                dismissLoading();
            }
        });
    }

    @Override
    public void setSyncData(boolean success, int code) {

    }

    private void onManageJumpPage() {
        reLogin(this);
    }

    @Override
    public void setCountryCodeData(List<CountryCode> data) {

    }

    @Override
    public void setPhoneCodeData(String data) {

    }

    @Override
    public void setSyncPhoneCodeData(String data) {

    }

    private void chooseItem(int posation) {
        switch (posation) {
            case 0:
                IMPORT_TYPE = 1;
                cleanInput();
                et_safty_code.setHint(getResources().getString(R.string.set_safty));
                rl_safty_code_again.setVisibility(View.VISIBLE);
                tv_mnemonic_word.setHint(getResources().getText(R.string.tips_input_help_rember_word));
//                tv_tips.setText(getResources().getText(R.string.tips_input_help_rember_word));
                iv_scan.setVisibility(View.GONE);
                break;
            case 1:
                IMPORT_TYPE = 3;
                cleanInput();
                et_safty_code.setHint(getResources().getString(R.string.set_safty));
                rl_safty_code_again.setVisibility(View.VISIBLE);
                tv_mnemonic_word.setHint(getResources().getText(R.string.tips_input_private_key));
//                tv_tips.setText(getResources().getText(R.string.tips_input_private_key));
                iv_scan.setVisibility(View.VISIBLE);
                break;
            case 2:
                IMPORT_TYPE = 2;
                cleanInput();
                rl_safty_code_again.setVisibility(View.GONE);
                et_safty_code.setHint(R.string.keystore_safty);
                tv_mnemonic_word.setHint(getResources().getText(R.string.tips_input_private_keystore));
//                tv_tips.setText(getResources().getText(R.string.tips_input_private_keystore));
                iv_scan.setVisibility(View.GONE);
                break;
            default:
                break;
        }
    }

    private void cleanInput() {
        tv_mnemonic_word.setText("");
        et_account_name.setText("");
        et_safty_code.setText("");
        et_safty_code_again.setText("");
    }

    @Override
    public void setFailure() {

    }

    @SuppressLint("SetTextI18n")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 扫描二维码/条码回传
        //todo 二维码 导入私钥回调
        if (requestCode == REQUEST_CODE_SCAN && resultCode == RESULT_OK) {
            if (data != null) {
                //返回的文本内容
                String content = data.getStringExtra(Intents.Scan.RESULT);
                LogUtil.error("ramon", "result: " + content);
                if (TextUtils.isEmpty(content)) {
                    toast("无效二维码");
                    return;
                }
                if (QRUtils.scanType(content) == 3) {
                    //解析私钥，填入私钥
                    String resPk = QRUtils.getContentString(content, 3);
                    tv_mnemonic_word.setText(resPk);
                }

            }
        }
    }

    @Override
    public void onSync() {
        LogUtil.error("ramon", "sync success");
        DataBaseManager.add_WalletToDb(walletInfo);
        if (UserUtils.setCurrentUserAddress(walletInfo.getAddress())) {
            DataManager.setUserInfo(walletInfo);
        }
        dismissLoading();
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                onManageJumpPage();
            }
        });
    }

    @Override
    public void onSyncFail(Object obj) {

    }

    @OnClick({R.id.bt_compare, R.id.iv_scan})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bt_compare:
//                startActivity(new Intent(this,MainActivity.class));
                setCode();
                break;
            case R.id.iv_scan:
                Intent intent = new Intent(this, ScanActivity.class);
                startActivityForResult(intent, REQUEST_CODE_SCAN);
                break;
            default:
                break;
        }
    }

}
